<template>
  <div class="app-container">
    <!-- 搜索模块 -->
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="字典类型" prop="scene">
        <el-select v-model="queryParams.type" placeholder="字典类型" size="small" style="width: 240px" @change="getList">
          <el-option v-for="dict in dictOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 图标权限模块 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['admin:region:form:add:post']" type="primary" plain icon="el-icon-date" size="mini"
          @click="handleAdd">新增字典项
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['admin:region:form:delete:{id}:delete']" type="danger" plain icon="el-icon-delete"
          size="mini" :disabled="multiple" @click="handleDelete">批量删除
        </el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>
    <!-- 展示模块 -->
    <el-table v-loading="loading" :data="region0List" @selection-change="handleSelectionChange" v-show="queryParams.type==3">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="一级区域名称" align="center" prop="name" ></el-table-column>
      <el-table-column label="备注" align="center" prop="desc" />
      <el-table-column
        v-if="hasPermi(['admin:budget:form:edit:post', 'system:clearsavefile:download:post', 'admin:budget:form:delete:{id}:delete'])"
        label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button v-hasPermi="['admin:budget:form:edit:post']" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['admin:budget:form:delete:{id}:delete']" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-table v-loading="loading" :data="regionList" @selection-change="handleSelectionChange" v-show="queryParams.type==0">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="一级区域名称" align="center" prop="region_0_name" ></el-table-column>
      <el-table-column label="二级区域名称" align="center" prop="name" ></el-table-column>
      <el-table-column label="备注" align="center" prop="desc" />
      <el-table-column
        v-if="hasPermi(['admin:budget:form:edit:post', 'system:clearsavefile:download:post', 'admin:budget:form:delete:{id}:delete'])"
        label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button v-hasPermi="['admin:budget:form:edit:post']" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['admin:budget:form:delete:{id}:delete']" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-table v-loading="loading" :data="rigList" @selection-change="handleSelectionChange" v-show="queryParams.type==1">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="name" ></el-table-column>
      <el-table-column label="型号" align="center" prop="model" ></el-table-column>
      <el-table-column label="备注" align="center" prop="desc" />
      <el-table-column
        v-if="hasPermi(['admin:budget:form:edit:post', 'system:clearsavefile:download:post', 'admin:budget:form:delete:{id}:delete'])"
        label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['admin:budget:form:delete:{id}:delete']" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-table v-loading="loading" :data="companyList" @selection-change="handleSelectionChange" v-show="queryParams.type==2">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="name" ></el-table-column>
      <el-table-column label="类型" align="center" prop="type" ></el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        v-if="hasPermi(['admin:budget:form:edit:post', 'system:clearsavefile:download:post', 'admin:budget:form:delete:{id}:delete'])"
        label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button v-hasPermi="['admin:budget:form:edit:post']" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['admin:budget:form:delete:{id}:delete']" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 文件上传|修改 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
       <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane label="一级区域" name="first">
          <el-form ref="regionForm0" :model="regionForm0" :rules="rules" label-width="80px">
            <el-form-item label="区域名称" prop="name">
              <el-input v-model="regionForm0.name" placeholder="名称" />
            </el-form-item>
            <el-form-item label="描述" prop="desc">
              <el-input v-model="regionForm0.desc" placeholder="描述" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="二级区域" name="second">
          <el-form ref="regionForm1" :model="regionForm1" :rules="rules" label-width="80px">
            <el-form-item label="一级区域" prop="region_0_id">
              <el-select v-model="regionForm1.region_0_id" placeholder="所属一级区域" size="small" style="width: 240px">
                <el-option v-for="dict in regionOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="区域名称" prop="name">
              <el-input v-model="regionForm1.name" placeholder="名称" />
            </el-form-item>
            <el-form-item label="描述" prop="desc">
              <el-input v-model="regionForm1.desc" placeholder="描述" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="钻机" name="third">
          <el-form ref="rigForm" :model="rigForm" :rules="rules" label-width="80px">
            <el-form-item label="名称" prop="name">
              <el-input v-model="rigForm.name" placeholder="名称" />
            </el-form-item>
            <el-form-item label="型号" prop="model">
              <el-input v-model="rigForm.model" placeholder="类型" />
            </el-form-item>
            <el-form-item label="描述" prop="desc">
              <el-input v-model="rigForm.desc" placeholder="描述" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="公司" name="fourth">
          <el-form ref="companyForm" :model="companyForm" :rules="rules" label-width="80px">
            <el-form-item label="名称" prop="name">
              <el-input v-model="companyForm.name" placeholder="名称" />
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-input v-model="companyForm.type" placeholder="类型" />
            </el-form-item>
            <el-form-item label="描述" prop="remark">
              <el-input v-model="companyForm.remark" placeholder="描述" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <!-- <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="区域" prop="name">
          <el-input v-model="form.name" placeholder="名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="类型" style="width: 100%;">
            <el-option v-for="dict in dictOptions" :key="dict" :label="dict" :value="dict" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div> -->
    </el-dialog>
  </div>
</template>
  
<script>
import { listRegionType, listRigType, listCompanyType, inspectHeaderAll, listRegionType0, addRegionType0,editRegionType0, addRegionType1, editRegionType1,
dataEche, editType, delType,addRigType,editRigType,delRigType,addCompanyType,editCompanyType,delCompanyType,delRegion0Type,delRegion1Type } from "@/api/vadmin/budget/dict/dictapi";
import chunkUpload from '@/utils/chunkUpload'
import { getToken } from "@/utils/auth";
import { Decrypt } from "@/utils/AesHmacMD5";

export default {
  name: "dict",
  data() {
    return {
      // 遮罩层
      loading: true,dictOptions:[{value:3,label:'一级区域'},{value:0,label:'二级区域'},{value:1,label:'钻机'},{value:2,label:'公司'}],regionOptions:[],
      // 选中数组
      ids: [],activeName: 'first',
      valNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模板表格数据
      region0List:[],regionList: [],rigList:[],companyList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 场景数据字典
      sceneOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,  // 当前页数
        pageSize: 10,  // 每页显示几个
        name: undefined,
        type: 3
      },
      // 表单参数
      regionForm0: {},regionForm1: {},rigForm: {},companyForm: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        path: [
          { required: true, validator: this.validatorPath(), trigger: "blur" }
        ]
      },
      chunkUpload: chunkUpload, // 文件上传
      uploadUrl: process.env.VUE_APP_BASE_API + '/admin/system/upload_fileM/', //文件上传的路径
      uploadData: {},
      headers: {
        Authorization: "Bearer " + getToken()
      },
    };
  },
  created() {
    // 初始化数字台账列表
    this.getList();
    this.getRegionList();
    // 查询应用场景字典
    // this.getDicts("explorate_type").then(response => {
    //   this.sceneOptions = response.data;
    // });
  },
  methods: {
    validatorPath() {
      return (rule, value, callback) => {
        if (this.form.id == undefined && !value) {
          return callback(new Error("模板文件不能为空"));
        } else {
          callback();
        }
      }
    },
    /** 查询区域列表 */
    getRegionList(){
      listRegionType0(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        var resData = JSON.parse(Decrypt(response.data))
        this.regionOptions = resData.results;

      });
    },
    getList() {
      this.loading = true;
      if(this.queryParams.type==3){
        listRegionType0(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          var resData = JSON.parse(Decrypt(response.data))
          this.region0List = resData.results;
          this.total = resData.count;
          this.loading = false;
        });
      }else if(this.queryParams.type==0){
        listRegionType(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          var resData = JSON.parse(Decrypt(response.data))
          this.regionList = resData.results;
          this.total = resData.count;
          this.loading = false;
        });
      }else if(this.queryParams.type==1){
        listRigType(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          var resData = JSON.parse(Decrypt(response.data))
          this.rigList = resData.results;
          this.total = resData.count;
          this.loading = false;
        });
      }else if(this.queryParams.type==2){
        listCompanyType(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          var resData = JSON.parse(Decrypt(response.data))
          this.companyList = resData.results;
          this.total = resData.count;
          this.loading = false;
        });
      }
      

    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        scene: undefined,
        path: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 文件上传按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增字典项";
      //一级区域
      this.regionForm0.id = '';
      // this.regionForm0.name = '';
      // this.regionForm0.desc = '';
      //二级区域
      this.regionForm1.id = '';
      // this.regionForm1.region_0_id = '';
      // this.regionForm1.name = '';
      // this.regionForm1.desc = '';
      //钻机
      this.rigForm.id = '';
      // this.rigForm.name = '';
      // this.rigForm.model = '';
      // this.rigForm.desc = '';
      //公司
      this.companyForm.id = '';
      // this.companyForm.name = '';
      // this.companyForm.type = '';
      // this.companyForm.remark = '';
      // if(this.queryParams.type==0){
      //   this.title = "区域导入";
      // }else if(this.queryParams.type==1){
      //   this.title = "钻机导入";
      // }else if(this.queryParams.type==2){
      //   this.title = "公司导入";
      // }
      
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$refs.uploadRef.clearFiles()
    },
    /** 提交按钮 */
    submitForm: function () {
      debugger
      if(this.activeName=='first'){
        this.$refs["regionForm0"].validate(valid => {
          if (valid) {
            if (this.regionForm0.id == undefined||this.regionForm0.id == '') {
              addRegionType0(this.regionForm0).then(response => {
                this.msgSuccess(response.msg);
                this.open = false;
                this.getList();
              });
            } else {
              editRegionType0(this.regionForm0).then(response => {
                this.msgSuccess(response.msg);
                this.open = false;
                this.getList();
              })
            }
          }
        });
      }else if(this.activeName=='second'){
        this.$refs["regionForm1"].validate(valid => {
          if (valid) {
            if (this.regionForm1.id == undefined || this.regionForm1.id == '') {
              addRegionType1(this.regionForm1).then(response => {
                this.msgSuccess(response.msg);
                this.open = false;
                this.getList();
              });
            } else {
              editRegionType1(this.regionForm1).then(response => {
                this.msgSuccess(response.msg);
                this.open = false;
                this.getList();
              });
            }
          }
        });
      }else if(this.activeName=='third'){
        this.$refs["rigForm"].validate(valid => {
          if (valid) {
            if (this.rigForm.id == undefined || this.rigForm.id == '') {
              addRigType(this.rigForm).then(response => {
                this.msgSuccess(response.msg);
                this.open = false;
                this.getList();
              });
            } else {
              editRigType(this.rigForm).then(response => {
                this.msgSuccess(response.msg);
                this.open = false;
                this.getList();
              })
            }
          }
        });
      }else if(this.activeName=='fourth'){
        this.$refs["companyForm"].validate(valid => {
          if (valid) {
            if (this.companyForm.id == undefined || this.companyForm.id == '') {
              addCompanyType(this.companyForm).then(response => {
                this.msgSuccess(response.msg);
                this.open = false;
                this.getList();
              });
            } else {
              editCompanyType(this.companyForm).then(response => {
                this.msgSuccess(response.msg);
                this.open = false;
                this.getList();
              })
            }
          }
        });
      }
      
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.valNames = selection.map(item => item.formCode);
      this.single = selection.length !== 1;
      this.multiple = selection.length < 2;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var ids=[],_this=this
      if(row.id!=undefined){
        ids = [row.id]
      }else{
         ids = this.ids;
      }
      const names = row.name || this.valNames
      this.$confirm('是否确认删除编码为"' + names + '"的数据项? 请谨慎操作！', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        if(_this.queryParams.type==0){
          return delRegion1Type({id:ids});
        }else if(_this.queryParams.type==1){
          return delRigType({id:ids});
        }else if(_this.queryParams.type==2){
          return delCompanyType({id:ids});
        }else if(_this.queryParams.type==3){
          return delRegion0Type({id:ids});
        }
        
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      });
    },
    // 场景字典翻译
    sceneFormat(row, column) {
      return this.selectDictLabel(this.sceneOptions, row.scene);
    },
    /** 文件下载 **/
    handleDownload(row) {
      this.download(row.path, row.name);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      if(this.queryParams.type==3){
        this.regionForm0 = row;
        this.open = true;
        this.activeName='first'
        this.title = "修改字典项";
      }else if(this.queryParams.type==0){
        debugger
        this.regionForm1 = row;
        this.open = true;
        this.activeName='second'
        this.title = "修改字典项";
      }else if(this.queryParams.type==1){
        this.rigForm = row;
        this.open = true;
        this.activeName='third'
        this.title = "修改字典项";
      }else if(this.queryParams.type==2){
        this.companyForm = row;
        this.open = true;
        this.activeName='fourth'
        this.title = "修改字典项";
      }
      
    },
    /** 文件上传成功调用的钩子函数 */
    handleSuccess(data) {
      inspectHeaderAll({ 'path': data.saveFile }).then(response => {
        var resData = JSON.parse(Decrypt(response.data))
        if (resData.bol) {
          this.form.path = data.saveFile
          this.$message.success('文件上传成功！');
          this.$refs.uploadRef.clearFiles()
        } else {
          this.onInspect(resData.repeat_values)
        }
      })

    },
    /** 文件上传失败调用的钩子函数 */
    onError() {
      this.form.path = undefined
      this.$message.error('文件上传失败！');
      this.$refs.uploadRef.clearFiles()
    },
    /** 重复列回显函数 */
    onInspect(data) {
      this.form.path = undefined
      this.$message.error('文件' + data + '列重复，请检查之后重新上传！');
      this.$refs.uploadRef.clearFiles()
    }
  }
};
</script>
  